package com.smarth.zhizulian.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gyf.barlibrary.BarHide;
import com.gyf.barlibrary.ImmersionBar;
import com.smarth.zhizulian.R;
import com.smarth.zhizulian.app.BaseActivity;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.jsinter.JSActivityInterface;
import com.smarth.zhizulian.jsinter.JSArticleInterface;
import com.smarth.zhizulian.jsinter.JSDrawInterface;
import com.smarth.zhizulian.jsinter.JSGlobalInterface;
import com.smarth.zhizulian.jsinter.JSVideoInterface;
import com.smarth.zhizulian.utils.UserUtils;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.ChromeClientCallbackManager;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 18865 on 2018/1/25.
 * +HongWei
 */

public class AgentWebActivity extends BaseActivity {
    @BindView(R.id.ll_main)
    LinearLayout llMain;
    @BindView(R.id.titlebar_titlebar)
    LinearLayout titlebarAll;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    private AgentWeb mAgentWeb;
    public static final String INTENT_URL = "INTENT_URL";
    public static final String INTENT_TITLE = "INTENT_TITLE";
    public static final String INTENT_BUNDLE = "INTENT_BUNDLE";
    public static final String INTENT_MODE = "INTENT_MODE";

    public static final int MODE_NORMAL = 0;
    public static final int MODE_VIDEO = 1;
    public static final int MODE_ACTIVITY = 2;

    private String mUrl;
    private String mTitle;
    private String mBundle;
    private int mMode;
    private LinearLayout.LayoutParams mLp;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mUrl = getIntent().getStringExtra(INTENT_URL);
        mTitle = getIntent().getStringExtra(INTENT_TITLE);
        mMode = getIntent().getIntExtra(INTENT_MODE, MODE_NORMAL);
        mBundle = getIntent().getStringExtra(INTENT_BUNDLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_agentweb);
        ButterKnife.bind(this);
        switch (mMode) {
            case MODE_VIDEO:
                initVideoTitleBar();
                break;
            default:
                initNormalTitleBar();
                break;
        }
        initWebView();
    }

    private void initWebView() {
        setTitlebar(mTitle, true);
        findViewById(R.id.titlebar_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mAgentWeb.back()) {// true表示AgentWeb处理了该事件
                    AgentWebActivity.this.finish();
                }
            }
        });
        mLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mLp.weight = 1;
        mAgentWeb = AgentWeb.with(this)//传入Activity or Fragment
                .setAgentWebParent(llMain, mLp)//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams ,第一个参数和第二个参数应该对应。
                .closeProgressBar()
                .setReceivedTitleCallback(new ChromeClientCallbackManager.ReceivedTitleCallback() {
                    @Override
                    public void onReceivedTitle(WebView view, String title) {
//                        ((TextView) findViewById(R.id.titlebar_title)).setText(title);
                        ((TextView) findViewById(R.id.titlebar_title)).setText(title);
                    }
                })
//                .setReceivedTitleCallback(mCallback) //设置 Web 页面的 title 回调
                .setWebViewClient(new WebViewClient() {
                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view, url, favicon);
                        if (url.startsWith(BaseConfig.NetWork.URL_VIDEO)) {
                            initVideoTitleBar();
                        } else {
                            initNormalTitleBar();
                        }
                    }

                    @SuppressLint("NewApi")
                    @Override
                    public WebResourceResponse shouldInterceptRequest(WebView view, final WebResourceRequest request) {
                        if (request != null && request.getUrl() != null) {
                            return super.shouldInterceptRequest(view, new WebResourceRequest() {
                                @Override
                                public Uri getUrl() {
                                    return Uri.parse(injectParams(request.getUrl().toString()));
                                }

                                @Override
                                public boolean isForMainFrame() {
                                    return request.isForMainFrame();
                                }

                                @Override
                                public boolean isRedirect() {
                                    return request.isRedirect();
                                }

                                @Override
                                public boolean hasGesture() {
                                    return request.hasGesture();
                                }

                                @Override
                                public String getMethod() {
                                    return request.getMethod();
                                }

                                @Override
                                public Map<String, String> getRequestHeaders() {
                                    return request.getRequestHeaders();
                                }
                            });
                        }
                        return super.shouldInterceptRequest(view, request);
                    }

                    @Override
                    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                        return super.shouldInterceptRequest(view, injectParams(url));
                    }
                })
                .createAgentWeb()//
                .ready()
                .go(mUrl);
        mAgentWeb.getJsInterfaceHolder().addJavaObject("myVideo", new JSVideoInterface(mContext));
        mAgentWeb.getJsInterfaceHolder().addJavaObject("activity", new JSActivityInterface(mContext));
        mAgentWeb.getJsInterfaceHolder().addJavaObject("article", new JSArticleInterface(mContext));
        mAgentWeb.getJsInterfaceHolder().addJavaObject("global", new JSGlobalInterface(mContext));
        mAgentWeb.getJsInterfaceHolder().addJavaObject("draw", new JSDrawInterface(mContext));
    }

    public static void openForVideo(Context context, String relationId) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_TITLE, "视频详情");
        i.putExtra(INTENT_URL, injectParams(BaseConfig.NetWork.URL_VIDEO + relationId));
        i.putExtra(INTENT_MODE, MODE_VIDEO);
        context.startActivity(i);
    }

    public static void openForActivity(Context context) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_TITLE, "活动详情");
        i.putExtra(INTENT_URL, injectParams(BaseConfig.NetWork.URL_ACTIVITY));
        i.putExtra(INTENT_MODE, MODE_ACTIVITY);
        context.startActivity(i);
    }


    //---old
    public static void openForStandard(Context context) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_URL, injectParams(BaseConfig.NetWork.URL_RULE));
        i.putExtra(INTENT_TITLE, "新手必读");
        context.startActivity(i);
    }

    public static void openForQuestion(Context context) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_URL, injectParams(BaseConfig.NetWork.URL_RULE));
        i.putExtra(INTENT_TITLE, "常见问题");
        context.startActivity(i);
    }

    public static void openForMoneyCheats(Context context) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_URL, injectParams(BaseConfig.NetWork.URL_RULE));
        i.putExtra(INTENT_TITLE, "赚钱秘籍");
        context.startActivity(i);
    }

    public static void openForArticle(Context context, String relationId) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_URL, injectParams((BaseConfig.NetWork.URL_ARTICLE + relationId)));
        i.putExtra(INTENT_TITLE, "文章详情");
        context.startActivity(i);
    }

    public static void openForDraw(Context context) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_URL, injectParams(BaseConfig.NetWork.URL_DRAW));
        i.putExtra(INTENT_TITLE, "幸运抽奖");
        context.startActivity(i);
    }

    public static void openForAgreement(Context context) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_URL, injectParams(BaseConfig.NetWork.URL_AGREEMENT));
        i.putExtra(INTENT_TITLE, "登录协议");
        context.startActivity(i);
    }

    public static void openForHongBaoRule(Context context) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_URL, injectParams(BaseConfig.NetWork.URL_HONGBAORULE));
        i.putExtra(INTENT_TITLE, "红包雨规则");
        context.startActivity(i);
    }

    public static void openForNotice(Context context, String url) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_URL, injectParams(url));
        i.putExtra(INTENT_TITLE, "公告");
        context.startActivity(i);
    }

    public static void openForMember(Context context) {
        Intent i = new Intent(context, AgentWebActivity.class);
        i.putExtra(INTENT_URL, injectParams(BaseConfig.NetWork.URL_MEMBER));
        i.putExtra(INTENT_TITLE, "会员等级");
        context.startActivity(i);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initVideoTitleBar() {
        titlebarAll.setVisibility(View.GONE);
        ivBack.setVisibility(View.VISIBLE);
        ImmersionBar.with(this)
                .reset()
                .transparentStatusBar()
                .fitsSystemWindows(false)
                .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
                .init();
    }

    private void initNormalTitleBar() {
        ivBack.setVisibility(View.GONE);
        titlebarAll.setVisibility(View.VISIBLE);
        ImmersionBar.with(this)
                .reset()
                .transparentStatusBar()
                .statusBarDarkFont(true)
                .fitsSystemWindows(false)
                .init();
    }

    @OnClick({R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                if (!mAgentWeb.back()) {// true表示AgentWeb处理了该事件
                    this.finish();
                }
                break;
        }
    }

    @Override
    protected void initStatusBar() {
    }

    @Override
    protected void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause(); //暂停应用内所有 WebView ， 需谨慎。
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    public static String injectParams(String url) {
        if (url != null && !url.contains("maicaitoken=") && UserUtils.isLogin()) {
            if (url.contains("?")) {
                return url + "&maicaitoken=" + UserUtils.getToken();
            } else {
                return url + "?maicaitoken=" + UserUtils.getToken();
            }
        } else {
            return url;
        }
    }
}
